package etnorservice.etnor_service.utils;

import etnorservice.etnor_service.domain.po.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtTokenUtil {

    private static final Logger logger = LoggerFactory.getLogger(JwtTokenUtil.class);

//    @Value("${jwt.secret}")
    public String jwtSecret="HfkjksFKLJISJFKLFKWJFQFIQWIOFJQOFFQGGSDGFFJIQOEUFIEJFIOQWEFHFQOK5FKOIQWUFFEFE423FIQEOFJHUEWHFKASKDLQWJIFSJDJKFHJIJWO";

    // ... 其他方法 ...

    /**
     * 生成JWT token
     *
     * @param user 用户信息
     * @return JWT token
     */
    public String generateToken(User user) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + 60 * 60 * 1000); // 有效期1小时

        return Jwts.builder()
                .setSubject(user.getAccount())
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .signWith(SignatureAlgorithm.HS512, jwtSecret)
                .compact();
    }

    /**
     * 验证JWT token的有效性
     *
     * @param token JWT token
     * @return 是否有效
     */
    public boolean validateToken(String token) {
        try {
            Claims claims = Jwts.parserBuilder()
                    .setSigningKey(jwtSecret)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();

            // 检查token是否已过期
            return !isTokenExpired(claims);
        } catch (ExpiredJwtException ex) {
            logger.warn("Token has expired", ex);
            return false;
        } catch (Exception e) {
            logger.error("Failed to validate token", e);
            return false;
        }
    }

    /**
     * 检查token是否已经过期
     *
     * @param claims token中的信息
     * @return 是否过期
     */
    private boolean isTokenExpired(Claims claims) {
        Date expiration = claims.getExpiration();
        return expiration.before(new Date());
    }
    /**
     * 从JWT token中获取账户信息
     *
     * @param token JWT token
     * @return 账户信息
     */
    public String getAccountFromToken(String token) {
        try {
            Claims claims = Jwts.parserBuilder()
                    .setSigningKey(jwtSecret)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();

            return claims.getSubject();
        } catch (Exception e) {
            logger.error("Failed to get account from token", e);
            return null;
        }
    }
}


